/**
 * @Author: yishen@mdashen.com
 * @Date: 2021-01-06 20:29:44
 * @LastEditTime: 2021-01-22 17:04:26
 * @Description: 主文件
 */
const Koa = require('koa')
const app = new Koa()
const views = require('koa-views')
const json = require('koa-json')
const onerror = require('koa-onerror')
const bodyparser = require('koa-bodyparser')
const logger = require('koa-logger')
const session = require('koa-generic-session')
const redisStore = require('koa-redis')
const jwtKoa = require('koa-jwt')

const { REDIS_CONF } = require('./conf/db')
const { isProd } = require('./utils/env')

// view
const errorViewRouter = require('./routes/view/error')
// api
const indexApiRouter = require('./routes/api/index')

// error handler
let onerrorConf = {}

if (isProd) {
  onerrorConf = {
    redirect: '/error',
  }
}

onerror(app, onerrorConf)

// middlewares
// const { SECRET } = require('./conf/constants')
// app.use(jwtKoa({ secret: SECRET }).unless({ path: [/^\/users\/login/] }))
app.use(
  bodyparser({
    enableTypes: ['json', 'form', 'text'],
  })
)
app.use(json())
app.use(logger())
app.use(require('koa-static')(__dirname + '/public'))

app.use(
  views(__dirname + '/views', {
    extension: 'ejs',
  })
)

// session 配置，下面字符串随便写的
app.keys = ['UIsdf_7878#$']
app.use(
  session({
    key: 'weibo.sid', // cookie name 不指定为'weibo.sid'的话默认是 'koa.sid'
    prefix: 'weibo:sess:', // redis key 的前缀，默认是 `koa:sess:`
    cookie: {
      path: '/',
      httpOnly: true, // 只能通过server端，去修改
      maxAge: 24 * 60 * 60 * 1000, // 毫秒
    },
    store: redisStore({
      all: `${REDIS_CONF.host}:${REDIS_CONF.port}`,
    }),
  })
)

// apiRouters
app.use(indexApiRouter.routes(), indexApiRouter.allowedMethods())
// viewRroutes
app.use(errorViewRouter.routes(), errorViewRouter.allowedMethods()) // 404注册到最后

// error-handling
app.on('error', (err, ctx) => {
  console.error('server error', err, ctx)
})

module.exports = app
